var authtree,
    $,
    table,
    form,
    layer,
    searchId = 0,
    postObj,
    currentTreeNode
    , selectPosts;
let orgMap = new Map();
let ognMap = new Map();

const storageValue = "sysUserTableWidths";

layui.config({
    base: '/static/lib/layuiadmin/'
}).extend({
    authtree_zimi: 'modules/authtree_zimi'
}).use(['table', 'layer', 'authtree_zimi', 'laytpl'], function () {
    $ = layui.$;
    table = layui.table;
    layer = layui.layer;
    laytpl = layui.laytpl;
    authtree = layui.authtree_zimi;

    $.ajax({
        url: '/sys-post-privilege/getOrgAndPost',
        type: 'post',
        success: function (res) {
            var trees = formatData(res.data, 'parentId', 'id', 'name', 'choiceFlag');
            authtree.render('#orgTree', trees, {
                inputname: 'authids[]',
                layfilter: 'lay-check-auth',
                autowidth: true,
                checkType: 'radio',
                flags: [3]
            });

            //调整机构树中radio框的样式
            $('span input[type=radio]').parent().parent().css('height','30px');

            authtree.on('change(lay-check-auth)', function (data) {
                // 获取所有已选中节点
                var checked = authtree.getChecked('#orgTree');
                postObj = checked[0];
                var value = eval("(" + postObj + ")");
                renderUserTable([value.orgId + '-' + value.postId]);

                // 改变人员的title
                var tmpOrg = orgMap.get(value.orgId);
                var orgName = tmpOrg ? tmpOrg.name : '';
                $('div.memberText').html(`<span style="color: #F72E29">${orgName}-${value.postName}</span>岗位有以下人员`);
            });

            authtree.showDept('#orgTree', 2);

            // 点击机构节点事件
            $('span[state="1"]').on('click', function (res) {
                postObj = null;
                $('div.memberText').html('');
            });

            // 点击机构节点事件
            $('span[state="2"]').on('click', function (res) {
                $("input[type='radio']").each(function (index, el) {
                    el.checked = false;
                });

                form.render('radio');

                let currentValue = JSON.parse($(this).attr('value').replace(/'/g, "\""));
                let obj = ognMap.get(currentValue.ognId);

                // 点击时岗位为默认岗位
                postObj = JSON.stringify({
                    orgId: currentValue.id
                    ,parentId: currentValue.id
                    ,orgName: currentValue.orgName
                    ,postName: obj.postName
                    ,id:0
                    ,postId:0
                    ,flag:3
                });

                obj = orgMap.get(currentValue.id);
                let postIds;

                if (obj.list && obj.list.length > 0) {
                    postIds = getOrgPosts(obj.list);

                } else {
                    postIds = [];
                }

                $('div.leaderText').html('aaaa');

                // 改变人员的title
                if (currentValue.parentId == 0) {
                    $('div.memberText').html(`<span style="color: #F72E29">${currentValue.orgName}</span>单位有以下人员`);
                } else {
                    $('div.memberText').html(`<span style="color: #F72E29">${currentValue.orgName}</span>部门有以下人员`);
                }

                // 查询人员
                renderUserTable(postIds);

                // 查询岗位
                renderOrgLeader(currentValue.id);
            });

        }
    });

});

function renderOrgLeader(orgId) {
    $.ajax({
        url: '/sys-org-leader/getLeader'
        ,data: {orgId: orgId}
        ,type: 'post'
        ,success: function (res) {
            if (res.code == 0) {


                if (res.data && res.data.length > 0) {
                    let msg = "";

                    for (var i = 0; i < res.data.length; i++) {
                        if (i > 0) {
                            msg += ', ';
                        }

                        msg += res.data[i].postName;
                    }

                    $('div.leaderText').html(`领导岗位：<span style="color: #F72E29">${msg}</span>`);
                } else {
                    $('div.leaderText').html(`领导岗位：暂无指定`);
                }

            } else {
                layer.msg(res.msg, {
                    offset: '15px'
                    , icon: 1
                    , time: 1000
                });
            }
        }
        ,error:function(e){
            layer.msg(e, {
                offset: '15px'
                , icon: 1
                , time: 1000
            });
        }
    });
}

function renderUserTable(nodeValue) {
    var widths = localStorage[storageValue] ? JSON.parse(localStorage[storageValue]) : [130, 250, 70, 100];

    layui.use('table', function () {
        table = layui.table;

        table.render({
            id: 'sysUserLoad'
            , elem: '#sysuser'
            , url: nodeValue.length > 0 ? '/sys-user/listByPosts' : null
            , method: 'post'
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , even: true//隔行变色
            , limits: [10, 20, 30, 50, 80, 100]//每页条数的选择项，默认：[10,20,30,50,80,100]。
            , limit: 10//每页显示的条数（默认：10）
            , height: 650
            , width: 1200
            , request: {}
            , where: nodeValue.length > 0 ? {postList: JSON.stringify(nodeValue)} : null
            , data: nodeValue.length > 0 ? null : []
            , cols: [[
                {field: 'userName', width: widths[0], title: '姓名', align: 'left', style: 'color: #009688;'}
                , {field: 'postName', width: widths[1], title: '岗位', align: 'left', templet: '#postTpl'}
                , {field: 'sexDesc', width: widths[2], title: '性别', align: 'center', templet: '#sexTpl'}
                , {field: 'userPhone', width: widths[3], title: '电话', align: 'center', templet: '#telTpl'}
                , {title: '操作', toolbar: '#barDemo', align: 'center'}
            ]]
            , page: true
            , done: function (res, curr, count) {
                selectPosts = nodeValue;
            }
        });

        //监听行工具事件
        table.on('tool(sysuser)', function (obj) {
            var data = obj.data;

            switch (obj.event) {
                case 'del':
                    layer.confirm('真的删除行么', function (index) {
                        delUser(data);
                    })

                    break;
                case  'edit':
                    editUser(data);

                    break;
                case 'info':
                    infoUser(data);

                    break;
            }
        });

        $('th').mouseup(function () {
            var tr = $(this).parent()["0"];
            var widths = [];
            for (var i = 0; i < tr.cells.length - 1; i++) {
                widths.push(tr.cells[i].clientWidth);
            }

            localStorage[storageValue] = JSON.stringify(widths);
        });
    });
}

/**
 * 添加用户
 */
function addUser() {
    if (!postObj) {
        parent.layer.msg('没有选择岗位，请选择岗位！', {icon: 5, time: 800});
        return;
    }

    var user = new Object();
    user.loginName = "";
    user.userName = "";
    user.userSex = 0;
    user.postList = [JSON.parse(postObj.replace(/'/g, "\""))];
    user.userEmail = "";
    user.userPhone = "";

    localStorage.user = JSON.stringify(user);
    layer.open({
        type: 2
        , title: '添加用户'
        , area: ['900px', '600px']
        , maxmin: false
        , content: 'sysUserAdd.html?type=add'
        , end: function (res) {
            renderUserTable(selectPosts);
        }
    });
}

/*
* @author: wh
* @description: 修改用户
* @date: 2018/12/24 15:19
* @param
* @return
*/
function infoUser(data) {
    localStorage.user = JSON.stringify(data);

    let index = layer.open({
        type: 2
        , title: '菜单权限'
        , area: ['900px', '610px']
        , btn: ['关闭']
        , maxmin: false
        , content: 'sysUserMenu.html'
        , yes: function (res) {
            layer.close(index);
        }
    });
}

/*
* @author: wh
* @description: 修改用户
* @date: 2018/12/24 15:19
* @param
* @return
*/
function editUser(data) {
    localStorage.user = JSON.stringify(data);

    layer.open({
        type: 2
        , title: '修改用户'
        , area: ['900px', '600px']
        , maxmin: false
        , content: 'sysUserAdd.html?type=edit'
        // , zIndex: layer.zIndex
        , end: function (res) {
            renderUserTable(selectPosts);
        }
    });
}

function delUser(data) {
    $.ajax({
        url: '/sys-user/delete',
        data: data,
        type: 'post',
        success: function (res) {
            layer.msg('删除成功', {
                offset: '15px'
                , icon: 1
                , time: 1000
            }, function () {
                renderUserTable(selectPosts);
            });

        }
    });
}

function usersearch() {
    var value = $('#selectUserName').val();

    if (!value || value.length == 0) {
        return layer.msg('请输入姓名后查询', {
            anim: 6
            , icon: 5
            , time: 1000
        });
    }

    if (!selectPosts || (selectPosts && selectPosts.length == 0)) {
        return layer.msg('请选择机构或岗位后查询姓名', {
            anim: 6
            , icon: 5
            , time: 1000
        });
        return;
    }

    let postList = selectPosts;

    table.reload('sysUserLoad', {
        'url': '/sys-user/listByPosts',
        where: {
            'userName': value,
            'postList': JSON.stringify(postList)
        },
        done: function (res) {

        }
    });
}

function userRecycle() {
    layer.open({
        type: 2,
        title: '用户回收',
        area: ['600px', '500px'],
        content: 'userRecycling.html',
        end: function (res) {
            refresh();
        }
    });
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData(values, pid, id, name, checked) {
    var tree = [],
        item,
        obj,
        tmpObj,
        ognObj;

    // 全局变量赋值
    orgMap.clear();
    ognMap.clear();

    let postMap = new Map();
    let orgList = [];
    let cateMap = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();

        item.name = values[i][name];
        item.value = JSON.stringify(values[i]).replace(/"/g, "'");
        item.checked = values[i][checked];
        item.list = [];

        switch (values[i].flag) {
            case 1:
                item.name = values[i].orgName;
                cateMap.set(values[i].orgId, item);
                tree.push(item);
                break;
            case 2:
                orgMap.set(values[i][id], item);
                orgList.push(values[i]);

                if (values[i][pid] == 0) {
                    ognMap.set(values[i][id], values[i]);
                }

                break;
            case 3:
                postMap.set(values[i][id], item);
                break;
        }
    }

    // 2)插入默认岗位
    for (var i = 0; i < orgList.length; i++) { // 遍历Array
        obj = orgMap.get(orgList[i][id]);
        ognObj = JSON.parse(obj.value.replace(/'/g, "\""));

        if (!orgList[i].roleId) continue;

        tmpObj = new Object();
        tmpObj.orgId = orgList[i][id];
        tmpObj.parentId = orgList[i][id];
        tmpObj.orgName = ognObj.orgName;

        ognObj = ognMap.get(orgList[i].ognId);
        tmpObj.postName = ognObj.postName;

        tmpObj.id = 0;
        tmpObj.postId = 0;
        tmpObj.flag = 3;

        item = new Object();
        item.name = tmpObj.postName;
        item.value = JSON.stringify(tmpObj).replace(/"/g, "'");
        item.checked = false;
        item.list = [];

        obj.list.push(item);
    }

    // 3)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {

        switch (values[i].flag) {
            case 1:
                break;
            case 2:
                if (values[i][pid] > 0) {
                    obj = orgMap.get(values[i][pid]);
                    obj.list.push(orgMap.get(values[i][id]));
                } else {
                    obj = cateMap.get(values[i].orgCateId);
                    obj.list.push(orgMap.get(values[i][id]));
                }

                break;
            case 3:
                obj = orgMap.get(values[i].orgId);

                if (obj.list.length > 0) {
                    obj.list.splice(obj.list.length - 1, 0, postMap.get(values[i][id]));
                } else {
                    obj.list.push(postMap.get(values[i][id]));
                }

                break;
        }
    }

    // 4)删除没有子项目的list
    removeList(tree, 0);

    return tree;
}

function removeList(list, level) {
    for (var i = list.length - 1; i >= 0; i--) {
        if (list[i].list && list[i].list.length == 0) {
            delete list[i].list;

            if (level == 0) {
                list.splice(i, 1);
            }
        } else {
            removeList(list[i].list, level + 1);
        }
    }
}

/**
 * 取得授权功能子节点Id一览
 */
function getOrgPosts(childs) {
    let result = [];
    let tmpNode, value;

    for (var i = 0; i < childs.length; i++) {
        tmpNode = childs[i];
        value = JSON.parse(tmpNode.value.replace(/'/g, "\""));

        if (value.flag != 1) {
            result.push(value.parentId + '-' + value.id);
        }

        if (tmpNode.list && tmpNode.list.length > 0) {
            result = result.concat(getOrgPosts(tmpNode.list));
        }
    }

    return result;
}